import React from 'react';
import { connect } from 'react-redux';
import { Button, Modal, Tooltip, Spin, Icon, message, Tabs, Popover } from 'antd';
import { messages } from 'share/common';
import CustomReportService
  from 'containers/data-center/report-management/custom-report/custom-report.service';
import 'styles/data-center/report-management/report-management.scss';
import SlideFrame from 'components/slide-frame';
import FullScreen from 'components/full-screen';
import CustomReport from 'containers/data-center/report-management/custom-report/index-refactor';
import NewCustomReport
  from 'containers/data-center/report-management/custom-report/new-custom-report';
import NewThirdPartyReport from 'containers/data-center/report-management/new-third-party-report';
import EditCustomDataModal from 'containers/data-center/report-management/edit-custom-data-modal';
import OtherSourceDataManage from 'containers/data-center/report-management/other-source-data-manage';
import { withRouter } from 'react-router';
import AdvancedTable from 'components/advanced-table'
import menuRoute from 'routes/menuRoute';
import Importer from "components/template/importer/index";
import ResizeTable from 'components/resize-table';
import { setCustomReportModalExpandedRow } from 'actions/cache';
const { SimpleTable } = AdvancedTable;
const { TabPane } = Tabs;

const confirm = Modal.confirm;

function mapStateToProps(state) {
  return {
    customReportModalExpandedRow: state.cache.customReportModalExpandedRow,
  };
}

@connect(mapStateToProps)

class ReportManagement extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      validateLoading: false,
      modalLoading: false,
      activeKey: 'reportManage',
      loading: true,
      //报表动态获取
      reportList: [],
      fullVisible: false, //自定义报表 第一层是否展示
      innerVisible: false, //自定义报表 图表详情编辑页是否展示 （第二层）
      currentEditReportData: '', //当前编辑 自定义报表的 数据
      dataModalColumns: [
        {
          title: messages('basic-10.key199')/*模型名称*/,
          key: "reportName",
          dataIndex: 'reportName',
          width: '30%',
          render: (text, record) => {
            if (!text) {
              return <span>-</span>
            }
            return (
              <Popover placement="topLeft" content={text}>
                <span>{text}</span>
              </Popover>
            )
          }
        },
        {
          title: messages('basic-10.key48')/*描述*/,
          key: "reportDesc",
          dataIndex: 'reportDesc',
          render: text => <span>{text ? <Popover placement="topLeft" content={text}>{text}</Popover> : ''}</span>
        },
        {
          title: messages('basic-10.key209')/*处理*/,
          key: "operation",
          width: 110,
          align: 'center',
          render: (text, record) => {
            return (
              record.reportType === 'SDRM' ?
              <span className='operation-area'>
                <a onClick={(e) => this.editSingleModal(e, record)}>
                  {messages('common.edit')/*编辑*/}
                </a>
              </span> : null
            )
          }
        }
      ],
      otherDataColumns: [
        {
          title: messages('basic-10.key211')/*外部数据源*/,
          key: "reportName",
          dataIndex: 'reportName',
          width: '30%',
          render: (text, record) => {
            if (!text) {
              return <span>-</span>
            }
            return (
              <Popover placement="topLeft" content={text}>
                <span>{text}</span>
              </Popover>
            )
          }
        },
        {
          title: messages('basic-10.key48')/*描述*/,
          key: "reportDesc",
          dataIndex: 'reportDesc',
          render: text => <span>{text ? <Popover placement="topLeft" content={text}>{text}</Popover> : ''}</span>
        },
        {
          title: messages('basic-10.key209')/*处理*/,
          key: "operation",
          width: 220,
          align: 'center',
          render: (text, record) => {
            return (
              <span className='operation-area'>
                <a onClick={(e) => this.editOtherSourceData(e, record)}>
                  {messages('common.edit')/*编辑*/}
                </a>
                <Importer
                  triggerNode={
                    <a onClick={e=>e.preventDefault()}>{messages('basic-10.key212')/*导入数据*/}</a>
                  }
                  totalError={(data)=>{ return data && data.failureEntities}}
                  uploadOptions={{
                    uploadUrl: `/report/api/outside/datasource/report/import?reportId=${record.id}`,
                    listenUrl: '/report/api/batch/transaction/logs',
                  }}
                  uploadResultOptions={{
                    userImportResponse: true,
                    method: 'post',
                    shouldDownloadErrorInfo: true,
                    showErrorTable: true,
                    errorUrl: `/report/api/outside/datasource/report/failed/export`,
                    getErrorTableVisible: result => result && result.failureEntities > 0
                  }}
                  templateOptions={{templateList: [{
                      downloadName: messages('basic-10.key240',{arg1: record.reportName})/*外部数据源：{arg1} 模板*/,
                      templateName: messages('basic-10.key240',{arg1: record.reportName})/*外部数据源：{arg1} 模板*/,
                      downloadUrl: `/report/api/outside/datasource/report/template/download?reportId=${record.id}`,
                    }]}}
                  onOk={this.advancedTableRefOtherData.getList}
                />
              </span>
            )
          }
        }
      ],

    };
    this.isOpenConfirm = false;
  }

  goToAuthorize = () => {
    window.open(((window.ISIE9 ? "#" : "") + menuRoute.getRouteItem('data-report-distribution', 'key').url), '_blank')
  }

  editSingleModal = (e, record) => {
    this.setState({validateLoading: true})
    CustomReportService.queryCustomModalHasUse(record.id).then((res)=>{
      if (res.data && !res.data.result) {
        this.setState({validateLoading: false})
        this.openSlideFrame(messages('basic-10.key213')/*编辑自定义数据模型*/, record, EditCustomDataModal);
      } else {
        this.setState({validateLoading: false}, ()=>{
          message.error(messages('basic-10.key241')/*当前数据源已被引用，不能被编辑*/)
        })
      }
    }).catch(()=>{this.setState({validateLoading: false})})
  }

  editOtherSourceData = (e, record) => {
    this.setState({validateLoading: true})
    CustomReportService.querySingleOtherDataHasUse(record.id).then((res)=>{
      if (res.data && !res.data.result) {
        this.setState({validateLoading: false})
        this.openSlideFrame(messages('basic-10.key214')/*编辑外部数据源*/, record, OtherSourceDataManage);
      } else {
        this.setState({validateLoading: false}, ()=>{
          message.error(messages('basic-10.key241')/*当前数据源已被引用，不能被编辑*/)
        })
      }
    }).catch(()=>{this.setState({validateLoading: false})})
  }

  //自定义报表 图表详情编辑页 返回提醒 是否展示（第二层） 用于点击浏览器返回 不要重复展示提示
  confirmOpened = (key) => {
    this.isOpenConfirm = key;
  };


  componentWillMount() {
    // 监听浏览器点击返回
    this.props.router.setRouteLeaveHook(
      this.props.route,
      this.routerWillLeave
    );
  }

  //浏览器返回 处理 阻止默认事件，走自己的 返回流程
  routerWillLeave = (nextLocation) => {
    if (this.state.innerVisible) {
      if (!this.isOpenConfirm) {
        window.editCustomReportCancelConfirm && window.editCustomReportCancelConfirm();
      }
      return false;
    } else if (this.state.fullVisible) {
      this.customReportRef.onPageCanceled();
      return false;
    } else {
      return true
    }
  };

  componentDidMount() {
    this.getReportAllList();
    this.dataModalService();
  }

  //获取报表list
  getReportAllList() {
    this.setState({
      loading: true
    });

    CustomReportService.getReportAllList()
      .then((res) => {
        let { data: reportList } = res;
        reportList = reportList.map(category => {
          let { reports } = category;
          if (!Array.isArray(reports)) {
            reports = [];
          }
          return {
            reportName: category.name,
            key: category.code,
            expand: true,
            children: reports.map(report => {
              report.key = report.id;
              report.reportDesc = report.reportDesc || '-';
              return report;
            })
          };
        });

        this.setState({
          reportList,
          loading: false
        });
      });
  }

  //编辑自定义报表详情
  goToReportDetail = (e, item) => {
    e.preventDefault();
    e.stopPropagation();
    if (item.reportType === 'UD') {
      this.setState({ fullVisible: true, currentEditReportData: item });
    }
  };

  changeExpand = (e, item) => {
    const { reportList } = this.state;
    item.expand = !item.expand;
    this.setState({
      reportList: [...reportList],
    });
  };

  addCustomReport = () => {
    this.openSlideFrame(messages('basic-10.key188')/*新增自定义报表*/, { id: 'new' });
  };

  goToEditCustom = (e, item) => {
    e.preventDefault();
    e.stopPropagation();
    if (item.reportType === 'UD') {
      this.openSlideFrame(messages('basic-10.key189')/*编辑自定义报表*/, item);
    } else if (item.reportType === 'SD') {
      this.openSlideFrame(messages('basic-10.key54')/*编辑外部报表*/, item, NewThirdPartyReport);
    } else {
      this.openSlideFrame(messages('basic-10.key190')/*编辑固定报表*/, item);
    }
  };

  //删除自定义报表
  deleteCustom = (e, item) => {
    e.preventDefault();
    e.stopPropagation();
    confirm({
      title: messages('basic-10.key2')/*确认删除*/,
      okText: messages('basic-10.key3')/*确认*/,
      cancelText: messages('common.cancel')/*取消*/,
      iconType: 'exclamation-circle',
      onOk: () => {
        CustomReportService.deleteCustomReport({ id: item.id })
          .then((res) => {
            if (res.status === 200) {
              message.success(messages('common.delete.successful')/*删除成功*/);
              this.getReportAllList();
            }
          });
      }
    });
  };

  //打开侧拉 编辑 外部报表
  openSlideFrame = (title, data, content) => {
    SlideFrame.open({
      title: title,
      width: '800px',
      afterClose: (obj) => {
        if (obj && obj.needRefresh) {
          switch (obj.key) {
            case 'modal':
              this.dataModalService();
              break;
            case 'other':
              this.advancedTableRefOtherData.getList();
              break;
            case 'default':
              this.getReportAllList();
              break;
          }
        }
      },
      params: data,
      content: content || NewCustomReport,
      hasFooter: true
    }, this);
  };

  //自定义报表 图表详情编辑页是否展示 （第二层）
  handleInnerVisible = (key) => {
    this.setState({ innerVisible: key });
  };

  renderReportManage = () => {
    const { reportList, loading } = this.state;
    return (
      <div className='report-manage-tab'>
        <div className="btn-wrap">
          <Button type='primary' onClick={this.addCustomReport} style={{ marginRight: 8 }}>
            {messages('basic-10.key188')/*新增自定义报表*/}
          </Button>
        </div>
        <Spin spinning={loading}>
          {
            reportList.map(item => {
              return (
                <div className="report-type-wrap" key={item.key}>
                  <div className="report-type-title">
                  <span onClick={(e) => this.changeExpand(e, item)} className="report-type-expand">
                    {item.expand ? <Icon type="minus-square-o"/> : <Icon type="plus-square-o"/>}
                  </span>&nbsp;&nbsp;
                    <span className="report-name">{item.reportName}</span>
                  </div>
                  {
                    item.expand ?
                      item.children.map(child => {
                        return (
                          <div
                            className={`report-type-card ${child.reportType === 'UD' ? 'hover' : ''}`}
                            onClick={(e) => this.goToReportDetail(e, child)}>
                            <div className="report-card-top">
                              <div className="report-card-name">{child.reportName}</div>
                              <div className="report-card-icon">
                                {child.reportType === 'UD' &&
                                <Tooltip title={messages('common.delete')/*删除*/}>
                                  <Icon className='delete-icon' onClick={(e) => {
                                    this.deleteCustom(e, child);
                                  }} type="delete"/>
                                </Tooltip>}
                                <Tooltip title={messages('common.edit')/*编辑*/}>
                                  <Icon className='edit-icon' onClick={(e) => {
                                    this.goToEditCustom(e, child);
                                  }} type="edit"/>
                                </Tooltip>
                              </div>
                            </div>
                            <div className="report-card-desc">{child.reportDesc}</div>
                          </div>
                        );
                      })
                      : null
                  }
                </div>
              );
            })
          }
        </Spin>
      </div>
    )
  }

  dataModalService = () => {
    this.setState({modalLoading: true});
    CustomReportService.getAllCustomModalList({page: 0, size: 100000}).then((res)=>{
      this.setState({modalList: res.data, modalLoading: false})
    }).catch(()=>{this.setState({modalLoading: false})})
  }

  otherDataService = (page, size) => {
    return CustomReportService.getOtherDataList({page, size})
  }

  addCustomDataModal = () => {
    this.openSlideFrame(messages('basic-10.key215')/*新建自定义数据模型*/, {id: 'new'}, EditCustomDataModal);
  }

  addOtherSourceData = () => {
    this.openSlideFrame(messages('basic-10.key216')/*新建外部数据源*/, {id: 'new'}, OtherSourceDataManage);
  }

  onExpandedRowsChange = (enabled,record) => {
    const { customReportModalExpandedRow } = this.props;
    if(enabled && !(customReportModalExpandedRow.indexOf(record.key) !== -1)){
      customReportModalExpandedRow.push(record.key)
    }else{
      customReportModalExpandedRow.delete(record.key)
    }
    this.props.dispatch(setCustomReportModalExpandedRow(customReportModalExpandedRow));
  };

  renderDataModal = () => {
    const { dataModalColumns, modalList } = this.state;
    const { customReportModalExpandedRow } = this.props;
    return (
      <div className='data-modal-tab' key={'data-modal-tab'}>
        <div className="btn-wrap-tab">
          <Button type='primary' onClick={this.addCustomDataModal} style={{ marginRight: 8 }}>
            {messages('basic-10.key215')/*新建自定义数据模型*/}
          </Button>
        </div>
        <div style={{margin: '12px 20px 0 20px'}}>
          <ResizeTable
            key={'data-modal-table'}
            dataSource={modalList}
            columns={dataModalColumns}
            size="middle"
            loading={this.state.modalLoading || this.state.validateLoading}
            rowKey={'id'}
            bordered
            onExpand={this.onExpandedRowsChange}
            // defaultExpandedRowKeys={customReportModalExpandedRow}
          />
        </div>
      </div>
    )
  }

  renderOtherData = () => {
    const { otherDataColumns, validateLoading } = this.state;

    return (
      <div className='other-data-tab' key={'other-data-tab'}>
        <div className="btn-wrap-tab">
          <Button type='primary' onClick={this.addOtherSourceData} style={{ marginRight: 8 }}>
            {messages('basic-10.key217')/*新增外部数据源*/}
          </Button>
        </div>
        <SimpleTable
          key={'other-data-table'}
          loading={validateLoading}
          rowKey={'id'}
          onRef={ref => this.advancedTableRefOtherData = ref}
          columns={otherDataColumns}
          service={this.otherDataService}
        />
      </div>
    )
  }

  render() {
    const { loading, fullVisible, currentEditReportData, activeKey } = this.state;

    return (
      <div className="report-management-wrap">
        <Tabs
          defaultActiveKey={'reportManage'}
          activeKey={activeKey}
          onChange={(e) => {
            this.setState({ activeKey: e });
          }}
        >
          <TabPane tab={messages('basic-10.key218')/*报表管理*/} key='reportManage'/>
          <TabPane tab={messages('basic-10.key219')/*数据模型管理*/} key='dataModal'/>
          <TabPane tab={messages('basic-10.key220')/*外部数据源管理*/} key='otherData'/>
        </Tabs>
        {activeKey === 'reportManage' && this.renderReportManage()}
        {activeKey === 'dataModal' && this.renderDataModal()}
        {activeKey === 'otherData' && this.renderOtherData()}
        {fullVisible && !loading &&
        <FullScreen animateIn="fadeIn" animateOut="fadeOut" style={{ background: '#f0f1f3' }}>
          <CustomReport
            onRef={ref => this.customReportRef = ref}
            customReportData={currentEditReportData}
            confirmOpened={this.confirmOpened}
            onCancel={() => this.setState({ fullVisible: false })}
            handleInnerVisible={this.handleInnerVisible}
          />
        </FullScreen>}
      </div>
    );
  }

  static contextTypes = {
    router: React.PropTypes.object
  };
}

export default withRouter(ReportManagement);
